package agent

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"time"

	"gitee.com/liuxuezhan/ar-platform/base-common/result"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/logic/agent"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 代理报表导出
func ExportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.StatisticRequest
		if err := httpx.Parse(r, &req); err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		l := agent.NewExportLogic(r.Context(), svcCtx)
		_data, err := l.Export(&req)
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
		} else {

			fileName := fmt.Sprintf("report-%d.xlsx", time.Now().Unix())
			w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
			w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))

			_, err = io.Copy(w, bytes.NewReader(_data))
			if err != nil {
				result.HttpErrorResult(r.Context(), w, err)
				return
			}
		}
	}
}
